<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>js异步编程之宏微任务拆解</title>
</head>
<body>
  <script>
    // function calculate() {
    //   for (let i = 0; i < num; i++) {
    //     count += num--
    //   }
    //   console.log(count)
    // }
    // 1.使用宏任务(setTimeout)改造
    function calculate() {
      for (let i = 0; i < 10000000; i++) {
        if (num <= 0) break
        count += num--
      }
      if (num > 0) {
        setTimeout(calculate)
      } else {
        console.log(count)
      }
    }
    // 2.使用微任务(Promise.then)改造
    // async function calculate() {
    //   const res = await Promise.resolve().then(_ => {
    //     for (let i = 0; i < num; i++) {
    //       count += num--
    //     }
    //     return count
    //   })
    //   console.log(res)
    // }
    let num = 987654321
    let count = 0
    calculate()
    console.log('main')
  </script>
</body>
</html>